﻿using ERPSystem.Common.Domains.Department;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using MediatR;

namespace BasicInformationCommon.API.BasicInformationCommons.DepartmentTrees
{
    public class DepartmentTreeQueryHandler : IRequestHandler<DepartmentTreeQueryCommand, Result>
    {
        private readonly IBaseRepository<DepartmentTree> _departmentTreeRepository;

        public DepartmentTreeQueryHandler(IBaseRepository<DepartmentTree> departmentTreeRepository)
        {
            _departmentTreeRepository = departmentTreeRepository;
        }
        /// <summary>
        /// 查询部门树形业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>

        public async Task<Result> Handle(DepartmentTreeQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result();
            try
            {
                var departmentTree = await(await _departmentTreeRepository.GetAll()).Where(c => c.Pid == 0).ToListAsync();
                List<PermissionCascaderDto> dtos = new List<PermissionCascaderDto>();
                foreach (var item in departmentTree)
                {
                    PermissionCascaderDto permissionCascader = new PermissionCascaderDto();
                    permissionCascader.label = item.DepartmentTreeName;
                    permissionCascader.value = item.DepartmentTreeId;
                    permissionCascader.children = await GetCascaders(item.DepartmentTreeId);
                    dtos.Add(permissionCascader);
                }
                result.Data = dtos;
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
        public async Task<List<PermissionCascaderDto>> GetCascaders(int pid = 0)
        {
            var list = await (await _departmentTreeRepository.GetAll()).Where(c => c.Pid == pid).ToListAsync();
            List<PermissionCascaderDto> dtos = new List<PermissionCascaderDto>();
            foreach (var item in list)
            {
                PermissionCascaderDto permissionCascader = new PermissionCascaderDto();
                permissionCascader.label = item.DepartmentTreeName;
                permissionCascader.value = item.DepartmentTreeId;
                permissionCascader.children = await GetCascaders(item.DepartmentTreeId);
                dtos.Add(permissionCascader);
            }
            return dtos;
        }
    }
}
